package com.hlxj.license.server.controller;
import com.hlxj.license.server.model.LicenseInfo;
import com.hlxj.license.server.service.LicenseInfoService;
import com.hlxj.license.server.util.DateUtil;
import com.hlxj.license.server.util.FileUtil;
import com.hlxj.license.server.util.RSAUtil;
import com.hlxj.license.server.util.StringUtil;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.Timestamp;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * @功能:【DecodeController 】
 * @作者:代守诚
 * @日期:2019/5/21
 * @时间:16:01
 */
@RestController
@RequestMapping("/decode")
public class DecodeController {

    private static final Logger logger = LogManager.getLogger(DecodeController.class);

    @Autowired
    private LicenseInfoService licenseInfoService;

    @RequestMapping(value = "/decrypt/privateKey")
    public Map<String, String> decryptByPrivateKey(@RequestBody String encodeData, HttpServletRequest request, HttpServletResponse response) {
        System.out.println(encodeData);
        String privateKey = FileUtil.readFileContent("privateKey");
        byte[] decodeData = null;
        try{
            byte[] data = StringUtil.stringToBytes(encodeData);
            System.out.println(data.length);
            decodeData = RSAUtil.decryptByPrivateKey(data, privateKey);
        }catch (Exception e){
            e.printStackTrace();
        }
        String target = new String(decodeData);

        String[] info = target.split(";");
        Map<String, String> computerMap = new HashMap<>();
        Arrays.asList(info).forEach(str ->{
            String[] computer = str.split("=");
            computerMap.put(computer[0], computer[1]);
        });


        //根据uuid获取是否存在这个信息，存在添加进入数据库
        LicenseInfo licenseInfo = licenseInfoService.getLicenseInfo(computerMap.get("UUID"));
        if(licenseInfo != null && StringUtils.isEmpty(licenseInfo.getCpuId())) {
            licenseInfo.setCpuId(computerMap.get("CPU"));
            licenseInfo.setMac(computerMap.get("MAC"));
            licenseInfo.setMainBoard(computerMap.get("Mainboard"));
            licenseInfo.setModTime(new Timestamp(System.currentTimeMillis()));

            licenseInfoService.updateLicenseInfo(licenseInfo);
        }

        StringBuilder dataStr = new StringBuilder(target);
        dataStr.append(";").append("endTime=").append(DateUtil.formatTimeStamp(licenseInfo.getEndTime()));
        logger.info(" ***********************" + licenseInfo.getEndTime());
        //生成加密文件和签名返回给用户端
        logger.info("私钥加密——公钥解密");
        byte[] encodedData = null;
        String sign = null;
        try{
            encodedData = RSAUtil.encryptByPrivateKey(dataStr.toString().getBytes(), privateKey);
            sign = RSAUtil.sign(encodedData, privateKey);
        }catch (Exception e){
            e.printStackTrace();
        }

        Map<String, String> signMap = new HashMap<>();
        signMap.put("encodedData", StringUtil.bytesToString(encodedData));
        signMap.put("sign", sign);
        return signMap;
    }

    @RequestMapping(value = "/check/useful", method = RequestMethod.POST)
    public boolean checkUseful(@RequestBody  String encodeData, HttpServletRequest request, HttpServletResponse response) {
        System.out.println(encodeData);
        String privateKey = FileUtil.readFileContent("privateKey");
        byte[] decodeData = null;
        try{
            byte[] data = StringUtil.stringToBytes(encodeData);
            decodeData = RSAUtil.decryptByPrivateKey(data, privateKey);
        }catch (Exception e){
            e.printStackTrace();
        }
        String target = new String(decodeData);
        System.out.println(target);
        String[] info = target.split(";");
        Map<String, String> computerMap = new HashMap<>();
        Arrays.asList(info).forEach(str ->{
            String[] computer = str.split("=");
            computerMap.put(computer[0], computer[1]);
        });

        //根据uuid获取是否存在这个信息，对比验证
        LicenseInfo licenseInfo = licenseInfoService.getLicenseInfo(computerMap.get("UUID"));

        if(licenseInfo == null ) {
            return false;
        }

        long endTime = licenseInfo.getEndTime().getTime();
        System.out.println(endTime);
        String cpuId = licenseInfo.getCpuId();
        String mac = licenseInfo.getMac();
        String mainBoard = licenseInfo.getMainBoard();
        System.out.println(target);
        long endTimeMap = DateUtil.getTime(computerMap.get("endTime"));
        System.out.println(endTime);
        System.out.println(endTime == endTimeMap);
        if(endTime == endTimeMap && cpuId.equals(computerMap.get("CPU")) && mac.equals(computerMap.get("MAC")) && mainBoard.equals(computerMap.get("Mainboard"))) {
            return true;
        }

        return false;
    }


}
